package plggnssclib

import "C"
import (
	"bufio"
	"dgo/goutils/utils"
	"fmt"
	"io"
	"os"
	"strings"
)

type filecfg struct {
	ip             string
	port           string
	clientSocketID string
	channel_read   string
	channel_write  string
	file_var_json  string
	channel_req    string
}

var concfg filecfg

func Initialization() {
	list := os.Args
	n := len(os.Args)
	if n < 2 {
		fmt.Println("Wrong number of parameters!\n")
		fmt.Println("***.exe  -f   file\n")
		fmt.Println("***.exe  -r   ip  port\n")
		os.Exit(1)
	}
	//memset(&concfg, 0, sizeof(concfg));
	if list[1] == "-f" && n == 3 {
		fmt.Printf("use file:%s\n", list[2])
		initfilecfg(list[2])
	} else {
		fmt.Println("Parameter error !\n")
		os.Exit(0)
	}
	if len(concfg.port) <= 0 || len(concfg.ip) == 0 {
		fmt.Println("Parsing failed !\n")
		fmt.Println("IP--%s:%d\n", concfg.ip, concfg.ip)
		os.Exit(1)
	}
}
func initfilecfg(file string) {
	//printf("%s\n",filename_init);
	filename, err := os.Open(file)
	if err != nil {
		fmt.Println("open file fail\n")
		return
	}
	//var Discard string
	rd := bufio.NewReader(filename)
	for {
		line, err := rd.ReadString('\n')
		if err != nil || io.EOF == err {
			break
		} else {
			//reg1 := regexp.MustCompile(`[^=] =%d`)
			//Discard := reg1.FindAllStringSubmatch(line, -1)
			if line == "END" {
				break
			} else if line[0] == '#' {
				continue
			} else if strings.Contains(line, "IP") {
				//fmt.Sscanf(line, "%[^=] =%[0-9a-zA-Z./]", Discard, concfg.ip)
				p := strings.Index(line, "=")
				concfg.ip = utils.Trim(strings.Replace(line[p+1:], "\n", "", -1))
			} else if strings.Contains(line, "PORT") {
				//fmt.Sscanf(line, "%[^=] =%d", Discard, &concfg.port)
				p := strings.Index(line, "=")
				concfg.port = utils.Trim(strings.Replace(line[p+1:], "\n", "", -1))
			} else if strings.Contains(line, "CHANNEL_READ") {
				//fmt.Sscanf(line, "%[^=] =%[0-9a-zA-Z./,_]", Discard, concfg.channel_read)
				p := strings.Index(line, "=")
				concfg.channel_read = strings.Replace(line[p+1:], "\n", "", -1)
			} else if strings.Contains(line, "CHANNEL_WRITE") {
				//fmt.Sscanf(line, "%[^=] =%[0-9a-zA-Z./_]", Discard, concfg.channel_write)
				p := strings.Index(line, "=")
				concfg.channel_write = strings.Replace(line[p+1:], "\n", "", -1)
			} else if strings.Contains(line, "CHANNEL_REQ") {
				//fmt.Sscanf(line, "%[^=] =%[0-9a-zA-Z./_]", Discard, concfg.channel_req)
				p := strings.Index(line, "=")
				concfg.channel_req = strings.Replace(line[p+1:], "\n", "", -1)
			} else if strings.Contains(line, "FILE_VRS_JSON") {
				//sscanf(key, "%s%s%d", Discard, Discard, &CKF->Port);
				//fmt.Sscanf(line, "%[^=] =%[0-9a-zA-Z./]", Discard, concfg.file_var_json)
				p := strings.Index(line, "=")
				concfg.file_var_json = strings.Replace(line[p+1:], "\n", "", -1)
			} else {
				//ID MODULE SERVICE SOL-TYPE SYS SRC FEQ
				fmt.Println("Unknown symbol:%s\n", line)
				//	return false;
			}
		}
	}
	defer filename.Close()
}
